import * as cornerstone from 'cornerstone-core';
import * as cornerstoneTools from 'cornerstone-tools';
import * as cornerstoneMath from 'cornerstone-math';
import * as cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import * as dicomParser from 'dicom-parser';
import Hammer from 'hammerjs';
// 主入口文件
export class CornerstoneViewer {
    constructor() {
        this.element = null;
        this.currentSeries = null;
        this.currentImageIndex = 0;
        this.onImageChange = null;
        this.imageIds = [];
        this.isInitialized = false;
    }

    async initializeCornerstone() {
        try {
            console.log('初始化 Cornerstone.js...454545454');
            
            // 检查库是否已加载
            if (!cornerstone || !cornerstoneTools || !cornerstoneWADOImageLoader || !dicomParser) {
                throw new Error('Cornerstone.js 库未正确加载');
            }
            
            // 配置 WADO Image Loader
            cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
            cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
            
            // 配置 Web Workers (可选，提高性能)
            if (cornerstoneWADOImageLoader.webWorkerManager) {
                const config = {
                    maxWebWorkers: navigator.hardwareConcurrency || 1,
                    startWebWorkersOnDemand: true,
                    taskConfiguration: {
                        decodeTask: {
                            initializeCodecsOnStartup: false,
                            usePDFJS: false,
                            strict: false
                        }
                    }
                };
                
                cornerstoneWADOImageLoader.webWorkerManager.initialize(config);
            }
            
            // 初始化 Cornerstone Tools
            cornerstoneTools.external.cornerstone = cornerstone;
            cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
            cornerstoneTools.external.Hammer = Hammer;
            
            // 添加全局错误处理
            cornerstoneTools.init({
                globalToolSyncEnabled: true,
                showSVGCursors: true,
                mouseEnabled: true,
                touchEnabled: true,
                preventHandleOutsideImage: true
            });
            // console.log('查询自定义函数',cornerstoneTools);
            

            //         console.log('当前工具状态:', cornerstoneTools.store.state.tools); 
            // //          cornerstoneTools.store.state.tools[0].svgCursor.iconGroupString=
            // //         `<path fill="ACTIVE_COLOR" d="M1411 541l-355 355 355 355 144-144q29-31 70-14 39 17
            // //   39 59v448q0 26-19 45t-45 19h-448q-42 0-59-40-17-39 14-69l144-144-355-355-355
            // //   355 144 144q31 30 14 69-17 40-59 40h-448q-26 0-45-19t-19-45v-448q0-42 40-59
            // //   39-17 69 14l144 144 355-355-355-355-144 144q-19 19-45 19-12
            // //   0-24-5-40-17-40-59v-448q0-26 19-45t45-19h448q42 0 59 40 17 39-14 69l-144
            // //   144 355 355 355-355-144-144q-31-30-14-69 17-40 59-40h448q26 0 45 19t19
            // //   45v448q0 42-39 59-13 5-25 5-26 0-45-19z"
            // // />`
            //         console.log('当前工具状态3:', cornerstoneTools.store.state.tools[0])
            //         console.log('当前工具状态4:', cornerstoneTools.store.state.tools.length)
            // 添加全局事件监听器来捕获错误
            document.addEventListener('cornerstoneToolsError', (event) => {
                console.warn('Cornerstone Tools 错误:', event.detail);
            });
            
            this.isInitialized = true;
            console.log('Cornerstone.js 初始化完成');


            
        } catch (error) {
            console.error('Cornerstone.js 初始化失败:', error);
            throw error;
        } finally { 
            
            
        }
    }

    async initialize(containerId) {
        if (!this.isInitialized) {
            await this.initializeCornerstone();
        }
        
        const container = document.getElementById(containerId);
        if (!container) {
            throw new Error(`找不到容器元素: ${containerId}`);
        }

        // 清空容器
        container.innerHTML = '';

        // 创建 Cornerstone 元素
        this.element = document.createElement('div');
        this.element.style.width = '100%';
        this.element.style.height = '100%';
        this.element.style.position = 'relative';
        this.element.style.backgroundColor = '#000';
        this.element.className = 'cornerstone-element';
        
        container.appendChild(this.element);
        
        // 启用 Cornerstone 元素
        cornerstone.enable(this.element);
        
        // 设置视口参数
        const viewport = cornerstone.getDefaultViewportForImage(this.element);
        cornerstone.setViewport(this.element, viewport);
        
        // 添加工具
        this.setupTools();
        
        // 添加事件监听器
        this.setupEventListeners();
        
        // 设置像素值显示
        this.setupPixelValueDisplay();
        
        console.log('CornerstoneViewer 初始化完成');
    }

    setupTools() {
        try {
            if (!this.element) {
                throw new Error('Element not found');
            }

            // 清除现有工具状态
            cornerstoneTools.clearToolState(this.element);

            // 添加基本工具
            cornerstoneTools.addTool(cornerstoneTools.PanTool);
            cornerstoneTools.addTool(cornerstoneTools.ZoomTool);
            cornerstoneTools.addTool(cornerstoneTools.WwwcTool);
            cornerstoneTools.addTool(cornerstoneTools.StackScrollMouseWheelTool);
            cornerstoneTools.addTool(cornerstoneTools.LengthTool);
            cornerstoneTools.addTool(cornerstoneTools.AngleTool);
            cornerstoneTools.addTool(cornerstoneTools.RectangleRoiTool);

            // 设置工具状态
            cornerstoneTools.setToolActive('Pan', { mouseButtonMask: 1 });
            cornerstoneTools.setToolActive('Zoom', { mouseButtonMask: 2 });
            cornerstoneTools.setToolActive('Wwwc', { mouseButtonMask: 4 });
            cornerstoneTools.setToolPassive('Length');
            cornerstoneTools.setToolPassive('Angle');
            cornerstoneTools.setToolPassive('RectangleRoi');

            // 禁用 labelmaps3D 相关功能
            if (cornerstoneTools.store && cornerstoneTools.store.state) {
                cornerstoneTools.store.state.series = [];
                cornerstoneTools.store.state.stacks = [];
            }

            // 设置工具配置
            const toolConfig = {
                preventHandleOutsideImage: true,
                mouseButtonMask: 1
            };

            // 应用工具配置
            Object.keys(cornerstoneTools.store.state.tools).forEach(toolName => {
                if (cornerstoneTools.store.state.tools[toolName]) {
                    cornerstoneTools.store.state.tools[toolName].configuration = {
                        ...cornerstoneTools.store.state.tools[toolName].configuration,
                        ...toolConfig
                    };
                }
            });

            console.log('工具设置完成');
        } catch (error) {
            console.error('设置工具时出错:', error);
            throw error;
        }
    }

    setupEventListeners() {
        try {
            // 监听图像渲染事件
            this.element.addEventListener('cornerstoneimagerendered', (event) => {
                try {
                    this.onImageRendered(event);
                } catch (error) {
                    // 忽略 labelmaps3D 相关错误
                    if (error.message && error.message.includes('labelmaps3D')) {
                        console.debug('忽略 labelmaps3D 相关错误');
                        return;
                    }
                    console.error('图像渲染事件处理错误:', error);
                }
            });
            
            // 监听视口变化事件
            this.element.addEventListener('cornerstoneviewportchanged', (event) => {
                try {
                    this.onViewportChanged(event);
                } catch (error) {
                    console.error('视口变化事件处理错误:', error);
                }
            });
            
            // 监听新图像事件
            this.element.addEventListener('cornerstonenewimage', (event) => {
                try {
                    this.onNewImage(event);
                } catch (error) {
                    console.error('新图像事件处理错误:', error);
                }
            });
            
            // 监听堆栈滚动事件
            this.element.addEventListener('cornerstonestackscroll', (event) => {
                try {
                    this.onStackScroll(event);
                } catch (error) {
                    console.error('堆栈滚动事件处理错误:', error);
                }
            });
            
            // 监听工具事件
            this.element.addEventListener('cornerstonetoolsmousedown', (event) => {
                try {
                    // 确保事件对象有效
                    if (!event.detail || !event.detail.event) {
                        console.warn('无效的鼠标事件对象');
                        return;
                    }
                } catch (error) {
                    console.error('工具鼠标按下事件处理错误:', error);
                }
            });
            
            this.element.addEventListener('cornerstonetoolsmousemove', (event) => {
                try {
                    // 确保事件对象有效
                    if (!event.detail || !event.detail.event) {
                        return;
                    }
                } catch (error) {
                    console.error('工具鼠标移动事件处理错误:', error);
                }
            });
            
            this.element.addEventListener('cornerstonetoolsmouseup', (event) => {
                try {
                    // 确保事件对象有效
                    if (!event.detail || !event.detail.event) {
                        return;
                    }
                } catch (error) {
                    console.error('工具鼠标释放事件处理错误:', error);
                }
            });
            
            // 键盘事件
            document.addEventListener('keydown', (e) => this.handleKeyDown(e));
            
            // 添加直接的滚轮事件监听器作为备用方案
            this.element.addEventListener('wheel', (event) => {
                this.handleWheelEvent(event);
            });
            
            // 添加全局错误处理
            window.addEventListener('error', (event) => {
                // 忽略 labelmaps3D 相关错误
                if (event.message && event.message.includes('labelmaps3D')) {
                    event.preventDefault();
                    console.debug('忽略 labelmaps3D 相关错误');
                    return;
                }
            });
            
            console.log('事件监听器设置完成');
            
        } catch (error) {
            console.error('设置事件监听器时出错:', error);
        }
    }

    // 设置序列数据
    async setSeriesData(series, imageIndex = 0, onImageChange = null) {
        this.currentSeries = series;
        this.currentImageIndex = imageIndex;
        this.onImageChange = onImageChange;
        
        if (!series || !series.images || series.images.length === 0) {
            console.warn('无效的序列数据');
            return;
        }
        
        console.log(`设置序列数据: ${series.images.length} 张图像`);
        
        try {
            // 创建图像ID数组
            this.imageIds = await this.createImageIds(series.images);
            
            if (this.imageIds.length === 0) {
                throw new Error('无法创建图像ID');
            }
            
            // 如果只有一张图像，直接显示
            if (this.imageIds.length === 1) {
                await this.displaySingleImage(this.imageIds[0]);
            } else {
                // 多张图像，设置为堆栈
                await this.displayImageStack(this.imageIds, imageIndex);
            }
            
            // 应用最佳窗宽窗位
            this.applyOptimalWindowLevel();
            
        } catch (error) {
            console.error('设置序列数据失败:', error);
            throw error;
        }
    }

    // 创建图像ID数组
    async createImageIds(images) {
        const imageIds = [];
        
        for (let i = 0; i < images.length; i++) {
            const image = images[i];
            try {
                // 创建 Blob URL
                const blob = new Blob([image.arrayBuffer], { type: 'application/dicom' });
                const imageId = `wadouri:${URL.createObjectURL(blob)}`;
                imageIds.push(imageId);
                
                console.log(`创建图像ID ${i + 1}/${images.length}: ${imageId}`);
                
            } catch (error) {
                console.warn(`创建图像ID失败 ${i + 1}:`, error);
            }
        }
        
        return imageIds;
    }

    // 显示单张图像
    async displaySingleImage(imageId) {
        try {
            console.log('显示单张图像:', imageId);
            
            const image = await cornerstone.loadImage(imageId);
            cornerstone.displayImage(this.element, image);
            
            // 自动适应窗口
            this.fitToWindow();
            
            // 创建DICOM信息覆盖层
            setTimeout(() => {
                this.createDicomOverlay();
                this.updateDicomOverlay();
            }, 200);
            
        } catch (error) {
            console.error('显示单张图像失败:', error);
            throw error;
        }
    }

    // 显示图像堆栈
    async displayImageStack(imageIds, currentImageIndex = 0) {
        try {
            console.log(`显示图像堆栈: ${imageIds.length} 张图像，当前索引: ${currentImageIndex}`);
            
            // 创建堆栈对象
            const stack = {
                imageIds: imageIds,
                currentImageIdIndex: currentImageIndex
            };
            
            // 加载并显示当前图像
            const image = await cornerstone.loadImage(imageIds[currentImageIndex]);
            cornerstone.displayImage(this.element, image);
            
            // 确保工具已初始化
            this.setupTools();
            
            // 设置堆栈状态
            cornerstoneTools.addStackStateManager(this.element, ['stack']);
            cornerstoneTools.addToolState(this.element, 'stack', stack);
            
            // 设置堆栈滚动工具
            cornerstoneTools.setToolActive('StackScrollMouseWheelTool', {});
            
            // 自动适应窗口
            this.fitToWindow();
            
            // 创建DICOM信息覆盖层
            setTimeout(() => {
                this.createDicomOverlay();
                this.updateDicomOverlay();
            }, 200);
            
        } catch (error) {
            console.error('显示图像堆栈失败:', error);
            throw error;
        }
    }

    // 导航到指定图像
    navigateToImage(index) {
        if (!this.imageIds || this.imageIds.length === 0) return;
        
        const maxIndex = this.imageIds.length - 1;
        const newIndex = Math.max(0, Math.min(index, maxIndex));
        
        if (newIndex === this.currentImageIndex) return;
        
        this.currentImageIndex = newIndex;
        
        try {
            if (this.imageIds.length === 1) {
                // 单张图像，重新显示
                this.displaySingleImage(this.imageIds[0]);
            } else {
                // 多张图像，使用堆栈滚动
                const stackData = cornerstoneTools.getToolState(this.element, 'stack');
                if (stackData && stackData.data && stackData.data.length > 0) {
                    const stack = stackData.data[0];
                    stack.currentImageIdIndex = newIndex;
                    cornerstone.loadImage(this.imageIds[newIndex]).then(image => {
                        cornerstone.displayImage(this.element, image);
                    });
                }
            }
            
            // 更新DICOM信息覆盖层
            this.updateDicomOverlay();
            
            if (this.onImageChange) {
                this.onImageChange(this.currentImageIndex);
            }
            
        } catch (error) {
            console.error('导航到图像失败:', error);
        }
    }

    // 下一张图像
    nextImage() {
        if (this.imageIds && this.currentImageIndex < this.imageIds.length - 1) {
            this.navigateToImage(this.currentImageIndex + 1);
        }
    }

    // 上一张图像
    previousImage() {
        if (this.imageIds && this.currentImageIndex > 0) {
            this.navigateToImage(this.currentImageIndex - 1);
        }
    }

    // 事件处理器
    onImageRendered(event) {
        const viewport = cornerstone.getViewport(this.element);
        console.log('图像渲染完成:', {
            scale: viewport.scale.toFixed(3),
            translation: `${viewport.translation.x.toFixed(1)}, ${viewport.translation.y.toFixed(1)}`,
            windowWidth: viewport.voi.windowWidth,
            windowCenter: viewport.voi.windowCenter
        });
        
        // 强制创建和更新DICOM信息覆盖层
        setTimeout(() => {
            this.createDicomOverlay();
            this.updateDicomOverlay();
        }, 100);
    }

    onViewportChanged(event) {
        // 视口变化时的处理
    }

    onNewImage(event) {
        console.log('新图像加载:', event.detail.image);
    }

    onStackScroll(event) {
        const newImageIndex = event.detail.newImageIdIndex;
        console.log(`onStackScroll: 图像索引从 ${this.currentImageIndex} 变为 ${newImageIndex}`);
        
        if (newImageIndex !== this.currentImageIndex) {
            this.currentImageIndex = newIndex;
            
            // 立即更新DICOM信息覆盖层
            this.updateDicomOverlay();
            
            // 稍微延迟一下再次更新，确保图像已经渲染
            setTimeout(() => {
                this.updateDicomOverlay();
            }, 50);
            
            if (this.onImageChange) {
                this.onImageChange(this.currentImageIndex);
            }
        }
    }

    // 滚轮事件处理
    handleWheelEvent(event) {
        if (!this.imageIds || this.imageIds.length <= 1) return;
        
        event.preventDefault();
        
        const direction = event.deltaY > 0 ? 1 : -1;
        const newIndex = this.currentImageIndex + direction;
        
        console.log(`handleWheelEvent: deltaY=${event.deltaY}, direction=${direction}, 当前索引=${this.currentImageIndex}, 新索引=${newIndex}`);
        
        if (newIndex >= 0 && newIndex < this.imageIds.length) {
            this.navigateToImage(newIndex);
        }
    }

    // 键盘事件处理
    handleKeyDown(event) {
        if (!this.element || !document.contains(this.element)) return;
        
        switch (event.key) {
            case 'ArrowUp':
            case 'ArrowLeft':
                event.preventDefault();
                this.previousImage();
                break;
            case 'ArrowDown':
            case 'ArrowRight':
                event.preventDefault();
                this.nextImage();
                break;
            case 'Home':
                event.preventDefault();
                this.navigateToImage(0);
                break;
            case 'End':
                event.preventDefault();
                if (this.imageIds) {
                    this.navigateToImage(this.imageIds.length - 1);
                }
                break;
            case 'r':
            case 'R':
                event.preventDefault();
                this.resetView();
                break;
            case 'f':
            case 'F':
                event.preventDefault();
                this.fitToWindow();
                break;
        }
    }

    // 应用最佳窗宽窗位
    applyOptimalWindowLevel() {
        if (!this.currentSeries) {
            console.warn('没有当前序列数据，无法应用最佳窗宽窗位');
            return;
        }

        try {
            // 动态导入DicomProcessor来分析窗宽窗位
            import('./dicomProcessor.js').then(({ DicomProcessor }) => {
                const processor = new DicomProcessor();
                const optimal = processor.analyzeOptimalWindowLevel(this.currentSeries);
                
                console.log(`应用最佳窗宽窗位: ${optimal.windowWidth}/${optimal.windowCenter} (预设: ${optimal.preset})`);
                
                // 应用推荐的窗宽窗位
                this.setWindowLevel(optimal.windowWidth, optimal.windowCenter);
                
                // 存储当前的窗宽窗位信息
                this.currentWindowLevel = optimal;
                
            }).catch(error => {
                console.error('导入DicomProcessor失败:', error);
                // 使用默认窗宽窗位
                this.setWindowLevel(1000, 500);
            });
            
        } catch (error) {
            console.error('应用最佳窗宽窗位失败:', error);
            // 使用默认窗宽窗位
            this.setWindowLevel(1000, 500);
        }
    }

    // 公共方法
    setWindowLevel(width, center) {
        try {
            const viewport = cornerstone.getViewport(this.element);
            viewport.voi.windowWidth = width;
            viewport.voi.windowCenter = center;
            cornerstone.setViewport(this.element, viewport);
            
            // 更新DICOM信息覆盖层中的窗宽窗位显示
            this.updateDicomOverlay();
        } catch (error) {
            console.error('设置窗宽窗位失败:', error);
        }
    }

    zoomIn() {
        try {
            const viewport = cornerstone.getViewport(this.element);
            viewport.scale *= 1.2;
            cornerstone.setViewport(this.element, viewport);
        } catch (error) {
            console.error('放大失败:', error);
        }
    }

    zoomOut() {
        try {
            const viewport = cornerstone.getViewport(this.element);
            viewport.scale *= 0.8;
            cornerstone.setViewport(this.element, viewport);
        } catch (error) {
            console.error('缩小失败:', error);
        }
    }

    fitToWindow() {
        try {
            cornerstone.fitToWindow(this.element);
        } catch (error) {
            console.error('适应窗口失败:', error);
        }
    }

    resetView() {
        try {
            cornerstone.reset(this.element);
        } catch (error) {
            console.error('重置视图失败:', error);
        }
    }

    rotate(degrees) {
        try {
            const viewport = cornerstone.getViewport(this.element);
            viewport.rotation += degrees;
            cornerstone.setViewport(this.element, viewport);
        } catch (error) {
            console.error('旋转失败:', error);
        }
    }

    flipHorizontal() {
        try {
            const viewport = cornerstone.getViewport(this.element);
            viewport.hflip = !viewport.hflip;
            cornerstone.setViewport(this.element, viewport);
        } catch (error) {
            console.error('水平翻转失败:', error);
        }
    }

    flipVertical() {
        try {
            const viewport = cornerstone.getViewport(this.element);
            viewport.vflip = !viewport.vflip;
            cornerstone.setViewport(this.element, viewport);
        } catch (error) {
            console.error('垂直翻转失败:', error);
        }
    }

    // 激活测量工具
    activateLengthTool() {
        try {
            // 先禁用其他测量工具
            cornerstoneTools.setToolPassive('Angle');
            cornerstoneTools.setToolPassive('RectangleRoi');
            cornerstoneTools.setToolPassive('Wwwc');
            
            // 激活长度测量工具
            cornerstoneTools.setToolActive('Length', { mouseButtonMask: 1 });
            console.log('长度测量工具已激活');
        } catch (error) {
            console.error('激活长度测量工具失败:', error);
        }
    }

    activateAngleTool() {
        try {
            // 先禁用其他测量工具
            cornerstoneTools.setToolPassive('Length');
            cornerstoneTools.setToolPassive('RectangleRoi');
            cornerstoneTools.setToolPassive('Wwwc');
            
            // 激活角度测量工具
            cornerstoneTools.setToolActive('Angle', { mouseButtonMask: 1 });
            console.log('角度测量工具已激活');
        } catch (error) {
            console.error('激活角度测量工具失败:', error);
        }
    }

    activateRectangleRoiTool() {
        try {
            // 先禁用其他测量工具
            cornerstoneTools.setToolPassive('Length');
            cornerstoneTools.setToolPassive('Angle');
            cornerstoneTools.setToolPassive('Wwwc');
            
            // 激活ROI测量工具
            cornerstoneTools.setToolActive('RectangleRoi', { mouseButtonMask: 1 });
            console.log('ROI测量工具已激活');
        } catch (error) {
            console.error('激活ROI测量工具失败:', error);
        }
    }

    // 重新激活窗宽窗位工具
    activateWwwcTool() {
        try {
            // 禁用测量工具
            cornerstoneTools.setToolPassive('Length');
            cornerstoneTools.setToolPassive('Angle');
            cornerstoneTools.setToolPassive('RectangleRoi');
            cornerstoneTools.setToolPassive('Pan');
            
            // 重新激活窗宽窗位工具
            cornerstoneTools.setToolActive('Wwwc', { mouseButtonMask: 1 });
            console.log('窗宽窗位工具已激活');
        } catch (error) {
            console.error('激活窗宽窗位工具失败:', error);
        }
    }

    // 激活移动工具
    activatePanTool() {
        try {
            // 禁用其他工具
            cornerstoneTools.setToolPassive('Wwwc');
            cornerstoneTools.setToolPassive('Length');
            cornerstoneTools.setToolPassive('Angle');
            cornerstoneTools.setToolPassive('RectangleRoi');
            
            // 激活移动工具
            cornerstoneTools.setToolActive('Pan', { mouseButtonMask: 1 });
            console.log('移动工具已激活');
        } catch (error) {
            console.error('激活移动工具失败:', error);
        }
    }

    // 清除测量
    clearMeasurements() {
        try {
            cornerstoneTools.clearToolState(this.element, 'Length');
            cornerstoneTools.clearToolState(this.element, 'Angle');
            cornerstoneTools.clearToolState(this.element, 'RectangleRoi');
            cornerstone.updateImage(this.element);
        } catch (error) {
            console.error('清除测量失败:', error);
        }
    }

    // 导出图像
    exportImage() {
        try {
            let enabledElement;
            try {
                enabledElement = cornerstone.getEnabledElement(this.element);
            } catch (error) {
                console.warn('获取enabled element失败:', error.message);
                return;
            }
            
            if (!enabledElement) {
                console.warn('元素未启用cornerstone，无法导出图像');
                return;
            }
            
            const canvas = enabledElement.canvas;
            const link = document.createElement('a');
            link.download = `dicom_image_${Date.now()}.png`;
            link.href = canvas.toDataURL('image/png');
            
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (error) {
            console.error('导出图像失败:', error);
        }
    }

    // 获取当前视口信息
    getViewportInfo() {
        try {
            return cornerstone.getViewport(this.element);
        } catch (error) {
            console.error('获取视口信息失败:', error);
            return null;
        }
    }

    // 创建DICOM信息覆盖层
    createDicomOverlay() {
        if (!this.element) return;
        
        // 检查是否已存在覆盖层
        let overlay = this.element.querySelector('.dicom-overlay');
        if (overlay) return overlay;
        
        // 创建覆盖层容器
        overlay = document.createElement('div');
        overlay.className = 'dicom-overlay';
        overlay.style.cssText = `
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 10;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: #00ff00;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.8);
        `;
        
        // 创建四个角落的信息区域
        const corners = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
        corners.forEach(corner => {
            const cornerDiv = document.createElement('div');
            cornerDiv.className = `dicom-info-${corner}`;
            cornerDiv.style.cssText = `
                position: absolute;
                padding: 8px;
                line-height: 1.4;
                white-space: pre-line;
                background: rgba(0, 0, 0, 0.6);
                border-radius: 4px;
                border: 1px solid rgba(0, 255, 0, 0.3);
            `;
            
            // 设置位置
            switch (corner) {
                case 'top-left':
                    cornerDiv.style.top = '0';
                    cornerDiv.style.left = '0';
                    break;
                case 'top-right':
                    cornerDiv.style.top = '0';
                    cornerDiv.style.right = '0';
                    cornerDiv.style.textAlign = 'right';
                    break;
                case 'bottom-left':
                    cornerDiv.style.bottom = '0';
                    cornerDiv.style.left = '0';
                    break;
                case 'bottom-right':
                    cornerDiv.style.bottom = '0';
                    cornerDiv.style.right = '0';
                    cornerDiv.style.textAlign = 'right';
                    break;
            }
            
            overlay.appendChild(cornerDiv);
        });
        
        this.element.appendChild(overlay);
        return overlay;
    }

    // 更新DICOM信息覆盖层
    updateDicomOverlay() {
    
      
        if (!this.currentSeries || !this.currentSeries.images) {
            console.log('updateDicomOverlay: 没有序列数据');
            return;
        }
        
        const overlay = this.createDicomOverlay();
        const currentImage = this.currentSeries.images[this.currentImageIndex];
        if (!currentImage) {
            console.log('updateDicomOverlay: 没有当前图像数据');
            return;
        }
        
        console.log(`updateDicomOverlay: 更新覆盖层，当前图像索引: ${this.currentImageIndex + 1}/${this.currentSeries.images.length}`);
        
        let viewport;
        try {
            viewport = cornerstone.getViewport(this.element);
        } catch (error) {
            console.warn('获取viewport失败:', error);
            viewport = { voi: { windowWidth: 1000, windowCenter: 500 } };
        }
        
        // 左上角：当前图像位置/总图像数
        const topLeft = overlay.querySelector('.dicom-info-top-left');
        if (topLeft) {
            const imagePosition = `${this.currentImageIndex + 1}/${this.currentSeries.images.length}`;
            console.log(`: ${imagePosition}`);
            topLeft.textContent = imagePosition;
        } else {
            console.warn('未找到左上角覆盖层元素');
        }
        
        // 左下角：kV、mA、层厚、WW/WL
        const bottomLeft = overlay.querySelector('.dicom-info-bottom-left');
      
        if (bottomLeft) {
            const kv = currentImage.kvp || 'N/A';
            const ma = currentImage.xRayTubeCurrent || currentImage.exposureTime || 'N/A';
            console.log('更新ma',currentImage);
            
            const sliceThickness = currentImage.sliceThickness ? `${currentImage.sliceThickness.toFixed(2)}mm` : 'N/A';
            const ww = Math.round(viewport.voi.windowWidth);
            const wl = Math.round(viewport.voi.windowCenter);
            bottomLeft.textContent = `kV: ${kv}  mA: ${ma}\n${sliceThickness}\nWW: ${ww}  WL: ${wl}`;
        }
        
        // 右上角：性别、年龄、序列名称
        const topRight = overlay.querySelector('.dicom-info-top-right');
        if (topRight) {
            const gender = currentImage.patientSex || 'N/A';
            const age = this.calculateAge(currentImage.patientBirthDate, currentImage.studyDate) || 'N/A';
            const seriesDesc = currentImage.seriesDescription || this.currentSeries.seriesDescription || 'N/A';
            
            topRight.textContent = `${gender} ${age}\n${seriesDesc}`;
        }
        
        // 右下角：图像尺寸、像素间距、像素值
        const bottomRight = overlay.querySelector('.dicom-info-bottom-right');
        if (bottomRight) {
            const imageSize = currentImage.imageData ? 
                `${currentImage.imageData.columns}×${currentImage.imageData.rows}` : 'N/A';
            const pixelSpacing = currentImage.pixelSpacing ? 
                `${currentImage.pixelSpacing[0].toFixed(2)}×${currentImage.pixelSpacing[1].toFixed(2)}mm` : 'N/A';
            
            bottomRight.textContent = `${imageSize}\n${pixelSpacing}\nV: --`;
        }
    }

    // 计算年龄
    calculateAge(birthDate, studyDate) {
        if (!birthDate || !studyDate) return null;
        
        try {
            // 解析日期格式 YYYYMMDD
            const birth = new Date(
                parseInt(birthDate.substr(0, 4)),
                parseInt(birthDate.substr(4, 2)) - 1,
                parseInt(birthDate.substr(6, 2))
            );
            
            const study = new Date(
                parseInt(studyDate.substr(0, 4)),
                parseInt(studyDate.substr(4, 2)) - 1,
                parseInt(studyDate.substr(6, 2))
            );
            
            let age = study.getFullYear() - birth.getFullYear();
            const monthDiff = study.getMonth() - birth.getMonth();
            
            if (monthDiff < 0 || (monthDiff === 0 && study.getDate() < birth.getDate())) {
                age--;
            }
            
            return `${age}Y`;
        } catch (error) {
            console.warn('计算年龄失败:', error);
            return null;
        }
    }

    // 添加鼠标移动事件来显示像素值
    setupPixelValueDisplay() {
        if (!this.element) return;
        
        this.element.addEventListener('mousemove', (event) => {
            if (!this.currentSeries || !this.currentSeries.images) return;
            
            const rect = this.element.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;
            
            // 获取图像坐标
            let enabledElement;
            try {
                enabledElement = cornerstone.getEnabledElement(this.element);
            } catch (error) {
                console.warn('获取enabled element失败:', error.message);
                return;
            }
            
            if (!enabledElement || !enabledElement.image) return;
            
            try {
                const imageCoords = cornerstone.pageToPixel(this.element, x, y);
                const pixelValue = this.getPixelValue(imageCoords.x, imageCoords.y);
                
                // 更新右下角的像素值显示
                const overlay = this.element.querySelector('.dicom-overlay');
                if (overlay) {
                    const bottomRight = overlay.querySelector('.dicom-info-bottom-right');
                    if (bottomRight) {
                        const currentImage = this.currentSeries.images[this.currentImageIndex];
                        if (currentImage) {
                            const imageSize = currentImage.imageData ? 
                                `${currentImage.imageData.columns}×${currentImage.imageData.rows}` : 'N/A';
                            const pixelSpacing = currentImage.pixelSpacing ? 
                                `${currentImage.pixelSpacing[0].toFixed(2)}×${currentImage.pixelSpacing[1].toFixed(2)}mm` : 'N/A';
                            
                            bottomRight.textContent = `X: ${Math.floor(imageCoords.x)} Y: ${Math.floor(imageCoords.y)}\n${pixelSpacing}\nV: ${pixelValue !== null ? pixelValue : '--'}`;
                        }
                    }
                }
            } catch (error) {
                // 静默处理错误
            }
        });
    }

    // 获取指定位置的像素值
    getPixelValue(x, y) {
        if (!this.currentSeries || !this.currentSeries.images) return null;
        
        const currentImage = this.currentSeries.images[this.currentImageIndex];
        if (!currentImage || !currentImage.imageData) return null;
        
        const imageData = currentImage.imageData;
        const { columns, rows, pixelData, bitsAllocated, pixelRepresentation } = imageData;
        
        // 检查坐标是否在图像范围内
        if (x < 0 || x >= columns || y < 0 || y >= rows) return null;
        
        const pixelIndex = Math.floor(y) * columns + Math.floor(x);
        
        try {
            let pixelValue;
            
            if (bitsAllocated === 16) {
                const byteIndex = pixelIndex * 2;
                if (byteIndex + 1 < pixelData.length) {
                    const lowByte = pixelData[byteIndex];
                    const highByte = pixelData[byteIndex + 1];
                    pixelValue = lowByte + (highByte << 8);
                    
                    // 处理有符号数据
                    if (pixelRepresentation === 1 && pixelValue > 32767) {
                        pixelValue -= 65536;
                    }
                } else {
                    return null;
                }
            } else {
                if (pixelIndex < pixelData.length) {
                    pixelValue = pixelData[pixelIndex];
                } else {
                    return null;
                }
            }
            
            return pixelValue;
        } catch (error) {
            console.warn('获取像素值失败:', error);
            return null;
        }
    }

    // 销毁
    destroy() {
        try {
            if (this.element) {
                // 移除覆盖层
                const overlay = this.element.querySelector('.dicom-overlay');
                if (overlay) {
                    overlay.remove();
                }
                
                cornerstone.disable(this.element);
            }
            
            // 清理 Blob URLs
            if (this.imageIds) {
                this.imageIds.forEach(imageId => {
                    if (imageId.startsWith('wadouri:blob:')) {
                        URL.revokeObjectURL(imageId.replace('wadouri:', ''));
                    }
                });
            }
            
        } catch (error) {
            console.error('销毁查看器失败:', error);
        }
    }
} 